export function getRandomFloat(min, max, float) {
  const value = Math.random() * (max - min) + min;
  if (float === undefined) return value;
  return Number(value.toFixed(float));
}

export function requestAnimationFrameTimeout(callback, delay) {
  let startTime = performance.now();

  function tick() {
    let time = performance.now();
    if (time - startTime >= delay) {
      callback();
    } else {
      requestAnimationFrame(tick);
    }
  }

  requestAnimationFrame(tick);
}

export function convertImageToBase64(src) {
  
  return new Promise((reslove) => {
    const img = new Image()
    img.src = src
    img.onload = () => {
      let canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      let ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      let dataUrl = canvas.toDataURL();
  
      reslove(dataUrl)
  
    }
  })
}

export function listenKeyboardArrowUp(...arg) {
  return listenKeyboard('ArrowUp', ...arg)
}
export function listenKeyboardArrowDown(...arg){
  return listenKeyboard('ArrowDown', ...arg)
}
export function listenKeyboardArrowLeft(...arg){
  return listenKeyboard('ArrowLeft', ...arg)
}
export function listenKeyboardArrowRight(...arg){
  return listenKeyboard('ArrowRight', ...arg)
}
export function listenKeyboardSpace(...arg){
  return listenKeyboard('Space', ...arg)
}
export function listenKeyboardEnter(...arg){
  return listenKeyboard('Enter', ...arg)
}

/**
 * listen keyboard event
 */
export function listenKeyboard(code, callback){

  if (!callback) return;

  /**
   * keyboard event handel
   */
  function handel (e) {
    if(e.code === code) {
      callback(e)
    }
  }
  /**
   * remove keyboard event handel
   */
  function remove(){
    window.removeEventListener('keydown', handel)
  }
  window.addEventListener('keydown', handel)
  return { remove }
}
